package view;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.TextFieldTreeCell;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

// 树形视图
public class TreeViewDemo extends Application {
	private Pane root = new Pane();
	private TreeView<String> tree = new TreeView<>();
	
	public static void main(String[] args) {
		launch(args);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void start(Stage stage) {
		
		tree.setFixedCellSize(30);
		tree.setEditable(true);	
		tree.setCellFactory(TextFieldTreeCell.forTreeView());	// 文本框编辑
		tree.setStyle("-fx-background-color: orange");
		
		// 肉分支
		TreeItem<String> meat = new TreeItem<>("meat");		// TreeItem显示的内容为节点的toString方法的返回值
		TreeItem<String> pork = new TreeItem<>("pork");
		TreeItem<String> chicken = new TreeItem<>("chicken");
		meat.getChildren().addAll(pork, chicken);
		
		// 水果分支
		TreeItem<String> fruit = new TreeItem<>("fruit");
		TreeItem<String> apple = new TreeItem<>("apple");
		TreeItem<String> peach = new TreeItem<>("peach");
		fruit.getChildren().addAll(apple, peach);
		
		// 食物主支
		TreeItem<String> food = new TreeItem<>("food");
		food.getChildren().addAll(meat, fruit);
		food.setExpanded(true);		// 延展内容
		
		tree.setRoot(food);
		root.getChildren().add(tree);
		
		Scene scene = new Scene(root, 400, 300);
		stage.setScene(scene);
		stage.show();
		
		// 选择内容的监听
		tree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<String>>() {

			@Override
			public void changed(ObservableValue<? extends TreeItem<String>> observable, TreeItem<String> oldValue,
					TreeItem<String> newValue) {
				System.out.println(newValue.getValue());
			}
		});
	}
}
